<template>
	<div class="stop_condition">
		<!-- 停止条件选择 -->
		<div class="config_line">
			<div class="label">停止条件：</div>
			<el-select v-model="stopType" class="config_input">
				<el-option label="手动停止" value="FOREVER" />
				<el-option label="按时间停止" value="DURATION" />
				<el-option label="按次数停止" value="EXECUTION" />
			</el-select>
		</div>

		<!-- 时间停止条件 -->
		<div class="time_stop config_line" v-show="stopType === 'DURATION'">
			<div class="label">最大运行时间：</div>
			<el-input-number v-model="timeValue" :min="1" :step="1" class="time_number"
				controls-position="right" />
			<el-select v-model="timeUnit" class="time_unit">
				<el-option value="时" />
				<el-option value="分" />
				<el-option value="秒" />
				<el-option value="毫秒" />
			</el-select>
		</div>

		<!-- 次数停止条件 -->
		<div class="execution_stop config_line" v-show="stopType === 'EXECUTION'">
			<div class="label">最大执行次数：</div>
			<el-input-number v-model="maxExecutions" :min="1" :max="100000" :step="1" class="execution_input"
				controls-position="right" />
			<div class="unit_label">次</div>
		</div>
	</div>
</template>

<script setup>
	import {
		ref,
		watch,
		computed
	} from 'vue'

	const props = defineProps({
		modelValue: {
			type: Object,
			default: () => ({
				maxExecutions: 0,
				maxTime: 0
			})
		}
	})

	const emit = defineEmits(['update:modelValue', 'update'])

	// 内部状态
	const stopType = ref("FOREVER") // FOREVER=用不停止, DURATION=达到时间, EXECUTION=达到次数
	const timeValue = ref(0)
	const timeUnit = ref('秒')
	const maxExecutions = ref(0)

	// 时间单位换算系数
	const unitMap = {
		'时': 60 * 60 * 1000,
		'分': 60 * 1000,
		'秒': 1000,
		'毫秒': 1
	}

	// 计算最终的maxTime（毫秒）
	const maxTime = computed(() => timeValue.value * unitMap[timeUnit.value])

	// 监听所有变化并触发更新
	watch(
		[stopType, maxTime, maxExecutions],
		([type, time, executions]) => {
			emit('update:modelValue', {
				type: type,
				maxExecutions: type === "EXECUTION" ? executions : 0,
				maxTime: type === "DURATION" ? time : 0
			});
			emit('update');
		}
	)

	// 处理单位变化时保持总时间不变（可选）
	const handleTimeUnitChange = (newUnit) => {
		const oldCoefficient = unitMap[timeUnit.value]
		const newCoefficient = unitMap[newUnit]
		timeValue.value = Math.round((timeValue.value * oldCoefficient) / newCoefficient)
	}

	// 重置状态方法（供父组件调用）
	const reset = () => {
		stopType.value = 1
		timeValue.value = 0
		timeUnit.value = '秒'
		maxExecutions.value = 0
	}

	defineExpose({
		reset
	})
</script>

<style lang="less" scoped>
	@import url('../assets/main.less');

	.stop_condition {
		// padding: 16px;
		// padding-left: 0px;

		.config_line {
			.config-line();

			.time_number,
			.execution_input {
				&::before {
					content: '';
					position: absolute;
					left: 0;
					top: 0;
					width: 2px;
					height: 100%;
					background: @primary-color;
				}
			}
		}

		.time_unit {
			width: 80px;
			.el-input__wrapper {
				background: rgba(@primary-color, 0.1);
			}
		}
	}
</style>